package com.lee.message.controller;

import com.lee.api.client.UserClient;
import com.lee.common.model.*;
import com.lee.message.service.IMessageService;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-10-08
 * Time: 11:27
 */
@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private UserClient userService;
    @Resource
    private IMessageService messageService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收者") @RequestParam("receiveUserId") @NotNull Long receiveUserId,
                          @ApiParam("站内信内容") @RequestParam("content") @NotNull String content) {

        // 1.获取当前登录用户并判断用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState() == 1) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2.不能给自己发送站内信
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给自己发送站内信");
        }
        // 3.判断接受者是否存在
        User receiver = userService.selectById(receiveUserId);
        if (receiver == null || receiver.getDeleteState() == 1) {
            // 返回错误信息
            return AppResult.failed("用户状态异常");
        }
        // 4.封装站内信对象
        Message updateMessage = new Message();
        updateMessage.setPostUserId(user.getId()); // 设置发送者Id
        updateMessage.setReceiveUserId(receiveUserId); // 设置接收者Id
        updateMessage.setContent(content); // 设置站内信内容
        // 5.调用Service发送站内信
        messageService.create(updateMessage);
        // 6.返回成功信息
        return AppResult.success("发送成功");
    }

    @ApiOperation("获取未读站内信数量")
    @GetMapping("getUnReadCount")
    public AppResult<Integer> getUnReadCount(HttpServletRequest request) {
        // 1.获取当前登录用户的Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        Long receiveUserId = user.getId();
        // 2.调用service
        Integer count = messageService.selectUnReadCount(receiveUserId);
        // 3.返回结果
        return AppResult.success(count);
    }

    @ApiOperation("获取当前用户的站内信列表")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 1.获取当前登录用户的Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        Long receiveUserId = user.getId();
        // 2.调用Service
        // 版本1
        // List<Message> messages = messageService.selectByReceiveUserId(receiveUserId);

        // 版本2-websocket改造
        List<Message> messages = messageService.selectPostUserByReceiveId(receiveUserId);
        // 3.返回结果
        return AppResult.success(messages);
    }

    @ApiOperation("查看站内信并更新为已读状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
            @ApiParam("站内信Id") @RequestParam("id") @NotNull Long id) {
        // 1.根据Id查询站内信是否存在
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1) {
            // 返回错误信息
            return AppResult.failed(ResultCode.ERROR_IS_NULL);
        }
        // 2.判断站内信的接收者是否为自己
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (message.getReceiveUserId() != user.getId()) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        // 3.调用service
        messageService.updateStateById(id, (byte) 1);
        // 4.返回成功信息
        return AppResult.success();
    }

    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("站内信Id") @RequestParam("repliedId") @NotNull Long repliedId,
                           @ApiParam("回复内容") @RequestParam("content") @NotNull String content) {
        // 1.校验当前站内信是否存在
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteState() == 1) {
            // 返回错误信息
            return AppResult.failed(ResultCode.ERROR_IS_NULL);
        }

        // 2.不能回复自己发送的站内信
        HttpSession session = request.getSession(false);
        User poster = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (poster.getId() == message.getPostUserId()) {
            return AppResult.failed("不能回复自己发送的站内信");
        }
        // 3.校验是否为发送给自己的站内信
        if (message.getReceiveUserId() != poster.getId()) {
            return AppResult.failed("不能回复别人的站内信");
        }
        // 4.校验发送者是否为禁言状态
        if (poster.getState() == 1) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 5.校验当前接收者是否存在
        User receiver = userService.selectById(message.getPostUserId());
        if (receiver == null || receiver.getDeleteState() == 1) {
            // 返回错误信息
            return AppResult.failed("用户状态异常");
        }
        // 6.封装回复站内信对象
        Message updateMessage = new Message();
        updateMessage.setPostUserId(poster.getId()); // 设置发送者
        updateMessage.setReceiveUserId(message.getPostUserId()); // 设置接收者
        updateMessage.setContent(content); // 设置回复内容
        updateMessage.setDeleteState((byte) 0); // 设置删除状态为未删除
        updateMessage.setState((byte) 0); // 设置状态为未读
        Date date = new Date(); // 设置创建更新日期
        updateMessage.setCreateTime(date);
        updateMessage.setUpdateTime(date);
        // 7.调用service
        messageService.reply(repliedId,updateMessage);
        // 8.返回结果
        return AppResult.success();

    }

    /**
     * 根据接收方和发送方id查询历史消息
     * @param request
     * @return
     */
    @ApiOperation("根据接收方和发送方id查询历史消息")
    @GetMapping("/gethistory")
    public AppResult<List<Message>> reply(HttpServletRequest request,
                           @ApiParam("接收方id") @RequestParam("receiveUserId") @NotNull Long receiveUserId) {
        // 获取当前登录用户（发送方）
        HttpSession session = request.getSession(false);
        User poster = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);

        // 调用service接口
        List<Message> messages = messageService.selectChatHistoryById(receiveUserId, poster.getId());
        // 返回结果
        return AppResult.success(messages);
    }
}
